﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace suirui.ZhuMu.Common
{
    class ModelTrans
    {
        public static TModel Trans<TModel, TModelDto>(TModelDto dto)
            where TModel : class
            where TModelDto : class
        {
            TModel model = Activator.CreateInstance(typeof(TModel)) as TModel;
            //获取TModel的属性集合
            PropertyInfo[] modlePropertys = typeof(TModel).GetProperties();
            //获取TModelDto的属性集合
            Type type = dto.GetType();
            PropertyInfo[] propertys = type.GetProperties();
            foreach (var property in propertys)
            {
                foreach (var mproperty in modlePropertys)
                {
                    //如果属性名称一致，则将该属性值赋值到TModel实例中
                    //这里可以用Attribute来实现成员的自定义映射
                    if (property.Name.Equals(mproperty.Name))
                    {
                        mproperty.SetValue(model, property.GetValue(dto));
                        break;
                    }
                }
            }

            //获取TModel的字段集合
            FieldInfo[] modelfieldInfos = typeof(TModel).GetFields();
            //获取TModelDto的字段集合
            FieldInfo[] fieldInfos = type.GetFields();
            foreach (var field in fieldInfos)
            {
                foreach (var mfield in modelfieldInfos)
                {
                    //如果字段名称一致，则将该字段值赋值到TModel实例中
                    if (field.Name.Equals(mfield.Name))
                    {
                        mfield.SetValue(model, field.GetValue(dto));
                        break;
                    }
                }
            }
            return model;
        }

        public static TModel TransJsonConvert<TModel, TModelDto>(TModelDto dto)
            where TModel : class
            where TModelDto : class
        {
            return JsonConvert.DeserializeObject<TModel>(JsonConvert.SerializeObject(dto));
        }
    }
}
